package com.ckd.flyingtrip.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ZoomControls;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MapViewLayoutParams;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.route.BikingRouteLine;
import com.baidu.mapapi.search.route.BikingRoutePlanOption;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteLine;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.bumptech.glide.Glide;
import com.ckd.flyingtrip.R;
import com.ckd.flyingtrip.constants.Constants;
import com.ckd.flyingtrip.javabean.CityBean;
import com.ckd.flyingtrip.javabean.UserInfoBean;
import com.ckd.flyingtrip.utils.BcUtils;
import com.ckd.flyingtrip.utils.DataCheck;
import com.ckd.flyingtrip.utils.GeoHasher;
import com.ckd.flyingtrip.utils.MapHelper;
import com.ckd.flyingtrip.utils.Tools;
import com.ckd.flyingtrip.utils.VolleyErrorUtils;
import com.ckd.flyingtrip.utils.map.BikingRouteOverlay;
import com.ckd.flyingtrip.utils.map.DrivingRouteOverlay;
import com.ckd.flyingtrip.utils.map.OverlayManager;
import com.ckd.flyingtrip.utils.map.WalkingRouteOverlay;
import com.ckd.flyingtrip.widge.SingleVolleyRequestQueue;
import com.google.gson.Gson;
import com.loc.bo;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;
import com.zaaach.citypicker.CityPickerActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;

public class MainActivity extends BaseActivity {

    @BindViews({R.id.index_linearLayout1_textView, R.id.index_linearLayout2_textView, R.id.index_linearLayout3_textView, R.id.index_linearLayout4_textView})
    List<TextView> textViews;
    @BindViews({R.id.index_linearLayout1_view, R.id.index_linearLayout2_view, R.id.index_linearLayout3_view, R.id.index_linearLayout4_view})
    List<View> views;

    @BindView(R.id.fl_station_info_name)
    TextView name;
    @BindView(R.id.fl_station_info_time)
    TextView time;
    @BindView(R.id.fl_station_info_battery)
    TextView battery;
    @BindView(R.id.fl_station_info_distance)
    TextView Infodistance;
    @BindView(R.id.fl_station_info_address)
    TextView address;
    @BindView(R.id.fl_station_info_phone)
    TextView phone;
    @BindView(R.id.fl_station_info_imageView)
    ImageView imageView;
    @BindView(R.id.fl_station_info_batteryll)
    LinearLayout batteryll;
    @BindView(R.id.fl_station_info_business)
    TextView business;
    @BindView(R.id.index_more)
    TextView more;

    @BindView(R.id.btn_my)
    ImageView btnMy;
    @BindView(R.id.btn_message)
    ImageView btnMessage;
    @BindView(R.id.bmapView)
    MapView mMapView;
    @BindView(R.id.btn_shiming)
    LinearLayout btnShiming;
    @BindView(R.id.drawerlayout_main_layout)
    LinearLayout drawerlayoutMainLayout;
    @BindView(R.id.btn_shuaxin)
    LinearLayout btnShuaxin;
    @BindView(R.id.btn_dingwei)
    LinearLayout btnDingwei;
    @BindView(R.id.btn_shaoma)
    LinearLayout btnShaoma;
    @BindView(R.id.btn_xiangling)
    LinearLayout btnXiangling;
    @BindView(R.id.btn_kefu)
    LinearLayout btnKefu;
    @BindView(R.id.btn_zuche)
    ImageView btnZuche;
    @BindView(R.id.cehualin)
    LinearLayout cehualin;
    @BindView(R.id.lin_city)
    LinearLayout linCity;
    @BindView(R.id.btn_city)
    LinearLayout btnCity;
    @BindView(R.id.txt_name)
    TextView txtName;
    @BindView(R.id.btn_xiangqing)
    TextView btnXiangqing;
    @BindView(R.id.fl_station_info)
    LinearLayout flStationInfo;
    @BindView(R.id.txt_city)
    TextView txtCity;
    @BindView(R.id.btn_jiahao)
    ImageView btnJiahao;
    private LocationClient mLocationClient;
    private BaiduMap mBaiduMap;
    private String sCurrentCity;
    private boolean changeCity = false;

    private BDLocation mBDLocationBean;
    private boolean is_mBDLocationBean;
    private LatLng currLatLng;
    private LatLng mapCenterLatLng;
    private String kefuPhone = "";
    private boolean isDC = false;
    // 换电点
    private List<LatLng> list_LatLng = new ArrayList<LatLng>();
    //    保存站点数据
    private List<CityBean> listCity = new ArrayList<CityBean>();
    //    mark文件
    private MarkerOptions option;
    //定位到坐标点后缩放比例
    public static final float MAP_ZOOM_DEFAULT = 12.0f;
    //    骑行路线
    private RoutePlanSearch mSearch;
    private BikingRouteOverlay bikingRouteOverlay;
    private View infoWindowView;
    private PlanNode targetNode;
    private int BatteryType = 48;
    private int hcbj = 0;
//    ==============================================

    private Map<String, CityBean> cityMapZddm = new HashMap<>();

    // 如果二次扫码30秒没扫描电池 hcbj改成0：请扫描柜子
    private CountDownTimer countDownTimer = null;
    public static MainActivity mainActivity;

    private String city = "";

    private Double firsLongitude = 0.0, firstLatitude = 0.0;

    private boolean aBoolean = true;

    private String siteType = "0";

    private Marker mMarkerA = null;
    private List<Marker> markers = new ArrayList<>();

    private Marker markerNot = null;
    private CityBean cityBeanNot = null;

    private CityBean cityBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        String path = "mapstyle.json";
//        String customStyleFilePath = getCustomStyleFilePath(MainActivity.this, path);
//        MapView.setCustomMapStylePath(customStyleFilePath);
        setContentView(R.layout.index);
        mainActivity = this;
        ButterKnife.bind(this);
        siteType = getIntent().getStringExtra("siteType");
        initTab(siteType);
        Log.i("用户信息", Tools.getUser());
        init();
        btnDingwei.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toast("正在定位中 请稍等...");
//                定位
                if (mLocationClient != null) {
                    is_mBDLocationBean = false;
                    mLocationClient.requestLocation();
                }
            }
        });
        btnShuaxin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toast("刷新成功...");
            }
        });
    }


    @SuppressLint("SetTextI18n")
    private void init() {
        btnMy.setImageResource(R.mipmap.activity_registered_icon1);
        volleQuery_Kefu();
        btnMy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //返回
//                startAction(MyselfCenterActivity.class);
                finish();
            }
        });
        btnCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Tools.isFastClick()) {
                    Intent intent = new Intent(MainActivity.this, CityPickerActivity.class);
                    intent.putExtra("type", "a");
                    intent.putExtra("city", city);
                    startActivityForResult(intent, 233);
                }
            }
        });

        initMapBaidu();
//
        getLocation();
        initMapLocation();
    }


    private void initTab(String str) {
        switch (str) {
            case "0":
                more.setText("查看更多换电站");
                break;
            case "1":
                more.setText("查看更多服务站");
                break;
            case "2":
                more.setText("查看更多维修站");
                break;
            case "3":
                more.setText("查看更多驿站");
                break;
        }
        more.setVisibility(View.GONE);
        for (int i = 0; i < textViews.size(); i++) {
            if (str.equals("" + i)) {
                textViews.get(i).setTextColor(ContextCompat.getColor(this, R.color.color_f3800f));
                views.get(i).setVisibility(View.VISIBLE);
            } else {
                textViews.get(i).setTextColor(ContextCompat.getColor(this, R.color.color_333));
                views.get(i).setVisibility(View.INVISIBLE);
            }
        }
    }


    public void volleyUserInfo() {
        final Gson mGson = new Gson();
        String url = Constants.QINGQIUGERENXINXI;
        StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                dismisProgressDialog();
                Log.i("用户信息", s);
                try {
                    JSONObject json = new JSONObject(s);
                    String code = json.getString("code");
                    String msg = json.getString("msg");
                    if (code.equals("1")) {
                        JSONObject dataInfo = json.getJSONObject("data");
                        String data = json.getString("data");
                        UserInfoBean userInfoBean = mGson.fromJson(data, UserInfoBean.class);
                        BcUtils.setUserInfo(userInfoBean);

                    } else {
                        Log.i("站好", "账号");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    dismisProgressDialog();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                dismisProgressDialog();
                VolleyErrorUtils.checkError(volleyError);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject json_url = new JSONObject();
                try {
                    json_url.put("userId", BcUtils.getUid());
                    json_url.put("userPhone", BcUtils.getUserInfo().getUserPhone());
                    json_url.put("token", BcUtils.getToken());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                map.put("inputParameter", DataCheck.signCheck(json_url.toString()));
                return map;
            }
        };
        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
    }


    /*
     * 查询客服电话
     * */
    public void volleQuery_Kefu() {
        final Gson mGson = new Gson();
        String url = Constants.KEFU;
        StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {

            @Override
            public void onResponse(String s) {
                dismisProgressDialog();
                Log.i("查询客服电话", s);
                //s为请求返回的字符串数据
                try {
                    JSONObject json = new JSONObject(s);
                    String code = json.getString("code");
                    if (code.equals("1")) {
                        String data = json.getString("data");
                        btnKefu.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                new AlertDialog.Builder(MainActivity.this).setTitle("确认拨打客服电话" + data)
                                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int which) {
                                                Tools.callPhone(MainActivity.this, data);
                                                dialog.dismiss();
                                            }
                                        })
                                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.dismiss();
                                            }
                                        }).show();
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {//创建请求参数

                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject json_url = new JSONObject();
                try {
                    json_url.put("userId", BcUtils.getUid());
                    json_url.put("token", BcUtils.getToken());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                map.put("inputParameter", DataCheck.signCheck(json_url.toString()));
                return map;
            }
        };
        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
    }


    @Override
    protected void onResume() {
        mMapView.onResume();
        volleyUserInfo();
        super.onResume();
        /*if (BcUtils.getUserInfo().getUserState().equals("2")) {
            btnShiming.setVisibility(View.VISIBLE);
            btnShiming.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    startAction(NameRenzhengActivity.class);
                }
            });
        } else {
            btnShiming.setVisibility(View.GONE);
        }*/

    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onRestart() {
        super.onRestart();

        volleyUserInfo();
    }

    //
    @Override
    protected void onDestroy() {
//        mLocationClient.stop();
//        mBaiduMap.setMyLocationEnabled(false);
//        if(mMapView!=null) {
//            mMapView = null;
//        }
        BcUtils.deleteId("timeYANZHENG");
        super.onDestroy();
    }


    /*
     *  邮政绑定电池码
     * */
    public void saomaHand(String content) {
        Log.i("扫描结果为", content);
        try {
            JSONObject dataJson = new JSONObject(content);
            String code = dataJson.getString("code");
            Log.i("扫描结果为JSON", code);


        } catch (JSONException e) {
            e.printStackTrace();

        }
    }

    /**
     * 初始化地图定位
     */

    private void initMapLocation() {
        mLocationClient = new LocationClient(getApplicationContext());
        LocationClientOption option = new LocationClientOption();
        option.setIsNeedAddress(true);// //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        option.setScanSpan(0);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setLocationNotify(false);//可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation
        // .getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setIgnoreKillProcess(false); //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
        option.setAddrType("all");
        option.setProdName("ipark");
        mLocationClient.registerLocationListener(new MyLocationListener());
        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }

    /*
     * 初始化地图配置
     * */
    private void initMapBaidu() {


        mMapView.showZoomControls(false);
        mMapView.showScaleControl(false);
        mBaiduMap = mMapView.getMap();

        mBaiduMap.setOnMapLoadedCallback(new BaiduMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                MapView.setMapCustomEnable(true);
            }
        });


        // 隐藏logo
        View child = mMapView.getChildAt(1);
        if (child != null && (child instanceof ImageView || child instanceof ZoomControls)) {
            child.setVisibility(View.INVISIBLE);
        }
//        地图状态
//        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NONE);

        mBaiduMap.setMyLocationEnabled(true);
        mBaiduMap.setTrafficEnabled(false);
        mBaiduMap.setBuildingsEnabled(false);
        BaiduMap.OnMapStatusChangeListener listener = new BaiduMap.OnMapStatusChangeListener() {
            /**
             * 手势操作地图，设置地图状态等操作导致地图状态开始改变。
             *
             * @param status 地图状态改变开始时的地图状态
             */
            @Override
            public void onMapStatusChangeStart(MapStatus status) {
                Log.e("sss", "---------------onMapStatusChangeStart");
                firsLongitude = status.target.longitude;
                firstLatitude = status.target.latitude;
            }

            /**
             * 手势操作地图，设置地图状态等操作导致地图状态开始改变。
             *
             * @param status 地图状态改变开始时的地图状态
             *
             * @param reason 地图状态改变的原因
             */
            //用户手势触发导致的地图状态改变,比如双击、拖拽、滑动底图
            //int REASON_GESTURE = 1;
            //SDK导致的地图状态改变, 比如点击缩放控件、指南针图标
            //int REASON_API_ANIMATION = 2;
            //开发者调用,导致的地图状态改变
            //int REASON_DEVELOPER_ANIMATION = 3;
            @Override
            public void onMapStatusChangeStart(MapStatus status, int reason) {
                Log.e("sss", "---------------onMapStatusChangeStart----------" + reason);
            }

            /**
             * 地图状态变化中
             *
             * @param status 当前地图状态
             */
            @Override
            public void onMapStatusChange(MapStatus status) {
                Log.e("sss", "---------------onMapStatusChange");
            }

            /**
             * 地图状态改变结束
             *
             * @param status 地图状态改变结束后的地图状态
             */
            @Override
            public void onMapStatusChangeFinish(MapStatus status) {
                Log.e("sss", "---------------onMapStatusChangeFinish");
                // 只监听用户手势引起的地图状态变化
                System.out.println("调用了请求获取站点信息");

                mapCenterLatLng = new LatLng(status.target.latitude, status.target.longitude);
                if (aBoolean == true) {
                    volleyZhandian(siteType);
                    aBoolean = false;
                }

                if (firsLongitude == 0.0 || firstLatitude == 0.0)
                    return;
                Double aDouble = MapHelper.distance(firsLongitude, firstLatitude, status.target.longitude, status.target.latitude);
                Log.e("sss", "距离：" + aDouble);
                if (aDouble < 8) {
                    return;
                }
                firsLongitude = 0.0;
                firstLatitude = 0.0;

                volleyZhandian(siteType);
                //显示加载弹窗，防止多次重复的获取
//                showProgressDialog("正在获取附近设备信息", false, false);

            }
        };
        ////设置地图状态监听
        mBaiduMap.setOnMapStatusChangeListener(listener);
        // 设置marker点击事件
        mBaiduMap.setOnMarkerClickListener(onMarkerClickListener);
//设置规划路径
        mSearch = RoutePlanSearch.newInstance();
        mSearch.setOnGetRoutePlanResultListener(onGetRoutePlanResultListener);
        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                initGone();
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {

                return false;
            }

        });
    }

    private void initGone() {
        try {
            if (markerNot != null)
                initNotMarker(markerNot, cityBeanNot, true);
            if (bikingRouteOverlay != null) {
                bikingRouteOverlay.setData(null);
                bikingRouteOverlay.removeFromMap();
            }
            if (infoWindowView != null) {
                mMapView.removeView(infoWindowView);
                linCity.setVisibility(View.GONE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 读取json路径
     */
    private String getCustomStyleFilePath(Context context, String customStyleFileName) {
        FileOutputStream outputStream = null;
        InputStream inputStream = null;
        String parentPath = null;
        try {
            inputStream = context.getAssets().open("customConfigdir/" + customStyleFileName);
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            parentPath = context.getFilesDir().getAbsolutePath();
            File customStyleFile = new File(parentPath + "/" + customStyleFileName);
            if (customStyleFile.exists()) {
                customStyleFile.delete();
            }
            customStyleFile.createNewFile();

            outputStream = new FileOutputStream(customStyleFile);
            outputStream.write(buffer);
        } catch (IOException e) {
            Log.e("CustomMapDemo", "Copy custom style file failed", e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                Log.e("CustomMapDemo", "Close stream failed", e);
                return null;
            }
        }
        return parentPath + "/" + customStyleFileName;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            try {
                if (linCity.getVisibility() == View.VISIBLE) {

                    if (bikingRouteOverlay != null) {
                        bikingRouteOverlay.setData(null);
                        bikingRouteOverlay.removeFromMap();
                    }
                    if (infoWindowView != null) {
                        mMapView.removeView(infoWindowView);
                        linCity.setVisibility(View.GONE);
                    }
                    return true;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            finish();
//            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * //返回按钮双击退出
     */
    private boolean isExit;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            isExit = false;
        }
    };

    private void exit() {
        if (!isExit) {
            isExit = true;
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);
            System.exit(0);
        }
    }

    /*
     * 规划路径
     * */
    private OnGetRoutePlanResultListener onGetRoutePlanResultListener = new OnGetRoutePlanResultListener() {
        @Override
        public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {
        }

        @Override
        public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {
        }

        @Override
        public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {
        }

        @Override
        public void onGetDrivingRouteResult(DrivingRouteResult drivingRouteResult) {
        }

        @Override
        public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {
        }

        @Override
        public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {
            try {
                //创建BikingRouteOverlay实例
                if (bikingRouteOverlay == null) {
                    bikingRouteOverlay = new BikingRouteOverlay(mBaiduMap);
                }
                if (bikingRouteResult.getRouteLines().size() > 0) {
                    //获取路径规划数据,(以返回的第一条路线为例）
                    //为BikingRouteOverlay实例设置数据
                    bikingRouteOverlay.setData(bikingRouteResult.getRouteLines().get(0));
                    //在地图上绘制BikingRouteOverlay
                    checkRoute(true);
                }
            } catch (Exception e) {
                e.printStackTrace();
                toast("路线规划失败");
            }
        }
    };

    public class MyDrivingRouteOverlay extends DrivingRouteOverlay {

        public MyDrivingRouteOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public BitmapDescriptor getStartMarker() {
            return null;
        }

        @Override
        public BitmapDescriptor getTerminalMarker() {
            return null;
        }
    }


    //clear图层后 重新显示路线规划及弹框
    private synchronized void checkRoute(boolean firstShow) {
        try {
            if (bikingRouteOverlay != null) {
                if (bikingRouteOverlay.getData() == null) {
                    return;
                }
//                bikingRouteOverlay.addToMap();
                if (infoWindowView == null) {
                    infoWindowView = getLayoutInflater().inflate(R.layout.layout_info_window, null);
                } else {
                    mMapView.removeView(infoWindowView);
                }
                TextView textView = infoWindowView.findViewById(R.id.tv_info);
                TextView infoWindowView_tv = infoWindowView.findViewById(R.id.layout_info_window_textView);

                BikingRouteLine bikingRouteLine = bikingRouteOverlay.getData();
                StringBuffer buffer = new StringBuffer();
                if (bikingRouteLine.getDistance() >= 1000) {
                    DecimalFormat decimalFormat = new DecimalFormat("0.##");
                    buffer.append(decimalFormat.format(((double) bikingRouteLine.getDistance()) / 1000d));
                    buffer.append("公里 ");
                } else {
                    buffer.append(Integer.toString(bikingRouteLine.getDistance()));
                    buffer.append("米 ");
                }
//                显示时分秒
                buffer.append("预计" + Tools.getDuration(bikingRouteLine.getDuration()) + "到达");
                textView.setText(buffer.toString());
                int num = Integer.parseInt(cityBeanNot.getSiteFullBattery48()) + Integer.parseInt(cityBeanNot.getSiteFullBattery60());
                int time = (Integer.parseInt(date2TimeStamp(cityBeanNot.getSiteBusinessEndTime(), "HH:mm")) -
                        Integer.parseInt(date2TimeStamp(cityBeanNot.getSiteBusinessStartTime(), "HH:mm"))) / 3600;
                if (siteType.equals("0"))
                    infoWindowView_tv.setText("可用电池数量：" + num + "块\n营业时间：" + time + "小时");
                else
                    infoWindowView_tv.setText("营业时间：" + time + "小时");

                Infodistance.setText("距您" + buffer.toString());

                ViewGroup.LayoutParams params = new MapViewLayoutParams.Builder()
                        .layoutMode(MapViewLayoutParams.ELayoutMode.mapMode)
                        .position(targetNode.getLocation())
                        .width(MapViewLayoutParams.WRAP_CONTENT)
                        .height(MapViewLayoutParams.WRAP_CONTENT)
                        .yOffset(-80)
                        .build();
                if (firstShow) {
                    linCity.setVisibility(View.VISIBLE);
                }


                mMapView.addView(infoWindowView, params);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     *
     * 地图点击marker
     * */
    BaiduMap.OnMarkerClickListener onMarkerClickListener = new BaiduMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {
            Log.e("marker", "地图点击marker");
            if (markerNot != null)
                initNotMarker(markerNot, cityBeanNot, true);
            final LatLng ll = marker.getPosition();
            cityBean = cityMapZddm.get(marker.getTitle());
            cityBeanNot = cityBean;
            markerNot = marker;
            if (!Tools.isEmpeyNull(cityBean)) {
                toast("已为您规划路线...");
            } else {
                Log.i("城市信息", cityBean.toString());
                txtName.setText(cityBean.getSiteAddr());
                name.setText(cityBean.getSiteName());
                time.setText(cityBean.getSiteBusinessStartTime() + "  —  " + cityBean.getSiteBusinessEndTime());
                address.setText("地址：" + cityBean.getSiteAddr());
                phone.setText("电话：" + cityBean.getSitePhone());
                Glide.with(MainActivity.this).load(cityBean.getSiteUrl()).into(imageView);
                String timeNow = new SimpleDateFormat("HH:mm").format(System.currentTimeMillis());
                if (Integer.parseInt(date2TimeStamp(cityBean.getSiteBusinessStartTime(), "HH:mm")) <
                        Integer.parseInt(date2TimeStamp(timeNow, "HH:mm")) &&
                        Integer.parseInt(date2TimeStamp(timeNow, "HH:mm")) <
                                Integer.parseInt(date2TimeStamp(cityBean.getSiteBusinessEndTime(), "HH:mm"))) {
                    business.setText("营业中");
                } else {
                    business.setText("休息中");
                }
                if (siteType.equals("0")) {
                    int num = Integer.parseInt(cityBean.getSiteFullBattery48()) + Integer.parseInt(cityBean.getSiteFullBattery60());
                    battery.setText("剩余" + num + "块电池");
                    batteryll.setVisibility(View.VISIBLE);
                } else {
                    batteryll.setVisibility(View.GONE);
                }

                initNotMarker(marker, cityBean, false);


//                txtCity.setText(cityBean.getZddz1());
                //满电池
//                int full_count48 = Integer.parseInt(cityBean.getFull_count48());
//                int full_count60 = Integer.parseInt(cityBean.getFull_count60());
//                int fullCount = full_count48 + full_count60;
//                tvFullBatteryNum.setText(String.valueOf(full_count60));
//                tvFullBatteryNuma.setText(String.valueOf(full_count48));
                //充电
//                int not_full_count48 = Integer.parseInt(cityBean.getNot_full_count48() + "");
//                int not_full_count60 = Integer.parseInt(cityBean.getNot_full_count60());
//                int noFullCount = not_full_count48 + not_full_count60;

//                tvRechargeBatteryNum.setText(String.valueOf(not_full_count60));
//                tvRechargeBatteryNuma.setText(String.valueOf(not_full_count48));
                btnXiangqing.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
//                        Intent intent = new Intent(MainActivity.this, MyCarActivity.class);
                        Intent intent = new Intent(MainActivity.this, XincheActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(Constants.POT_DETAIL, cityBean);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                });
                boolean isHdd = false;
                for (int j = 0; j < list_LatLng.size(); j++) {
                    LatLng point = list_LatLng.get(j);

                    // 是否点击的是 换电点（有可能是 我的位置）
                    if (ll.equals(point)) {
                        isHdd = true;
                    }
                }

                if (!isHdd) {
                    return true;
                }
                try {
                    MyLocationData myLocationData = mBaiduMap.getLocationData();

                    PlanNode stNode = PlanNode.withLocation(new LatLng(myLocationData.latitude, myLocationData.longitude));
                    PlanNode enNode = PlanNode.withLocation(ll);
                    targetNode = enNode;
                    mSearch.bikingSearch((new BikingRoutePlanOption())
                            .from(stNode)
                            .to(enNode)
                            // ridingType  0 普通骑行，1 电动车骑行
                            // 默认普通骑行
                            .ridingType(1));
                } catch (Exception e) {
                    e.printStackTrace();
                    toast("网络不流畅..请稍后再试");
                }
            }
            return false;
        }
    };

    private void initNotMarker(Marker marker, CityBean cityBean, boolean aBoolean) {
        View view_mark = LayoutInflater.from(MainActivity.this).inflate(R.layout.layout_map_maker, null);
        ImageView ivBattery = (ImageView) view_mark.findViewById(R.id.iv_battery);
        if (aBoolean)
            switch (siteType) {
                case "0":
                    ivBattery.setImageResource(R.mipmap.main0);
                    break;
                case "1":
                    ivBattery.setImageResource(R.mipmap.main2);
                    break;
                case "2":
                    ivBattery.setImageResource(R.mipmap.main3);
                    break;
                case "3":
                    ivBattery.setImageResource(R.mipmap.main4);
                    break;
            }
        else
            switch (siteType) {
                case "0":
                    ivBattery.setImageResource(R.mipmap.main_not0);
                    break;
                case "1":
                    ivBattery.setImageResource(R.mipmap.main_not2);
                    break;
                case "2":
                    ivBattery.setImageResource(R.mipmap.main_not3);
                    break;
                case "3":
                    ivBattery.setImageResource(R.mipmap.main_not4);
                    break;
            }
        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromView(view_mark);
        marker.setIcon(bitmap);
    }

    @OnClick({R.id.index_linearLayout1, R.id.index_linearLayout2, R.id.index_linearLayout3, R.id.index_linearLayout4, R.id.index_more, R.id.fl_station_info_toHere})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.index_linearLayout1:
                markerNot = null;
                cityBeanNot = null;
                siteType = "0";
                initTab(siteType);
                for (int i = 0; i < markers.size(); i++) {
                    markers.get(i).remove();
                }
                volleyZhandian(siteType);
                initGone();
                break;
            case R.id.index_linearLayout2:
                markerNot = null;
                cityBeanNot = null;
                siteType = "1";
                initTab(siteType);
                for (int i = 0; i < markers.size(); i++) {
                    markers.get(i).remove();
                }
                volleyZhandian(siteType);
                initGone();
                break;
            case R.id.index_linearLayout3:
                markerNot = null;
                cityBeanNot = null;
                siteType = "2";
                initTab(siteType);
                for (int i = 0; i < markers.size(); i++) {
                    markers.get(i).remove();
                }
                volleyZhandian(siteType);
                initGone();
                break;
            case R.id.index_linearLayout4:
                markerNot = null;
                cityBeanNot = null;
                siteType = "3";
                initTab(siteType);
                for (int i = 0; i < markers.size(); i++) {
                    markers.get(i).remove();
                }
                volleyZhandian(siteType);
                initGone();
                break;
            case R.id.index_more:
                break;
            case R.id.fl_station_info_toHere:
                switch (siteType) {
                    case "0":
                        break;
                    case "1":
                        intent = new Intent(this, ServiceShopDetailActivity.class);
                        intent.putExtra("text", (Serializable) cityBean);
                        startActivity(intent);
                        break;
                    case "2":
                        break;
                    case "3":
                        break;
                }
                break;
        }
    }

    /**
     * 实现定位回调
     */
    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取经纬度相关（常用）的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明
            if (location != null) {
                city = location.getCity();

                if (changeCity) {
                    changeCity = false;
                    return;
                }
                if (location.getLongitude() < 10 || location.getLatitude() < 10) {

                    return;
                }

                MyLocationData locData = new MyLocationData.Builder()
                        .accuracy(location.getRadius())
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                        .direction(location.getDirection())
                        .latitude(location.getLatitude())
                        .longitude(location.getLongitude()).build();
                mBaiduMap.setMyLocationData(locData);

                Log.d("qyy", "lat" + (int) location.getLatitude());
                Log.d("qyy", "lng" + (int) location.getLongitude());
                sCurrentCity = location.getCity();
                txtCity.setText(sCurrentCity);
                mBDLocationBean = location;
                LocChangeAction(mBDLocationBean, true);

            }
        }
    }


    private void LocChangeAction(BDLocation mBDLocationBean, boolean isNeedAnim) {
        try {
            if (!is_mBDLocationBean) {
                // 移动到 我的位置
                currLatLng = new LatLng(mBDLocationBean.getLatitude(),
                        mBDLocationBean.getLongitude());
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(currLatLng);
                if (isNeedAnim) {
                    mBaiduMap.animateMapStatus(u);
                }
            }
            is_mBDLocationBean = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /*
     * 根据经纬度获取站点信息
     * */
    public void volleyZhandian(String siteType) {
        final Gson mGson = new Gson();
        String url = Constants.SHOUYEZHANDIAN;
        StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {

            @Override
            public void onResponse(String s) {
                dismisProgressDialog();
                Log.i("获取站点信息", s);
                //s为请求返回的字符串数据
                try {
                    JSONObject json = new JSONObject(s);
                    String code = json.getString("code");
                    if (code.equals("1")) {
                        JSONArray data = json.getJSONArray("data");

                        if (data.length() > 0) {
                            list_LatLng.clear();
                            cityMapZddm.clear();
                            listCity.clear();
                            for (int i = 0; i < data.length(); i++) {
                                String srt = String.valueOf(data.getJSONObject(i));
                                CityBean city = mGson.fromJson(srt, CityBean.class);
                                Log.i("城市位置信息", city.toString());
                                listCity.add(city);
                                try {
                                    LatLng l = new LatLng(Double.parseDouble(city.getSiteLatitude()), Double.parseDouble(city.getSiteLongitude()));
                                    list_LatLng.add(l);
                                } catch (NumberFormatException e) {
                                    e.printStackTrace();
                                    toast("数据解析失败");
                                }
                                cityMapZddm.put(city.getSiteNum(), city);
                            }
//                            Log.i("listCity", listCity.get(0).toString());
//                            Log.i("list_LatLng", list_LatLng.get(0).toString());
                            mBaiduMap.clear();
                            checkRoute(false);
                            startMapAction(false);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {//创0建请求参数

                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject json_url = new JSONObject();
                try {
                    json_url.put("userId", BcUtils.getUid());
                    json_url.put("latitude", mapCenterLatLng.latitude);
                    json_url.put("longitude", mapCenterLatLng.longitude);
                    json_url.put("siteType", siteType);
                    json_url.put("userArea", Constants.CITYID);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                map.put("inputParameter", DataCheck.signCheck(json_url.toString()));

                return map;
            }
        };
        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
    }


    /**
     * 根据坐标点绘制Marker
     */
    @SuppressLint("InflateParams")
    private void showLineMarker() {
        Log.i("sizeList", list_LatLng.size() + "");
        Log.i("sizeList", listCity.size() + "");
        markers.clear();
        for (int i = 0; i < list_LatLng.size(); i++) {
            // 构建marker图标
            View view_mark = LayoutInflater.from(MainActivity.this).inflate(R.layout.layout_map_maker, null);
            CityBean zdjgFormBean = listCity.get(i);
            if (zdjgFormBean == null) {
                return;
            }
            ImageView ivBattery = (ImageView) view_mark.findViewById(R.id.iv_battery);
            LinearLayout linbuju = view_mark.findViewById(R.id.linbuju);
            TextView tvBatteryNumber = (TextView) view_mark.findViewById(R.id.tv_right);
//            判断是否需要隐藏

            switch (siteType) {
                case "0":
                    ivBattery.setImageResource(R.mipmap.main0);
                    break;
                case "1":
                    ivBattery.setImageResource(R.mipmap.main2);
                    break;
                case "2":
                    ivBattery.setImageResource(R.mipmap.main3);
                    break;
                case "3":
                    ivBattery.setImageResource(R.mipmap.main4);
                    break;
            }

            /*switch (zdjgFormBean.getSiteType()) {
                case "0":
                    ivBattery.setImageResource(R.mipmap.main0);
                    break;
                case "1":
                    ivBattery.setImageResource(R.mipmap.main1);
                    break;
                case "2":
                    ivBattery.setImageResource(R.mipmap.main2);
                    break;
                case "3":
                    ivBattery.setImageResource(R.mipmap.main3);
                    break;
                case "4":
                    ivBattery.setImageResource(R.mipmap.main4);
                    break;
            }*/

//            if (zdjgFormBean.getRegistStatus() != null) {
//                if (Integer.parseInt(zdjgFormBean.getRegistStatus()) >= 1) {
//                    ivBattery.setVisibility(View.VISIBLE);
//                    tvBatteryNumber.setVisibility(View.VISIBLE);
//                } else {
//                    ivBattery.setVisibility(View.GONE);
//                    tvBatteryNumber.setVisibility(View.GONE);
////                    Log.i("隐藏编号", zdjgFormBean.getZdmc1());
//                }
//            }
//            String zddz = (zdjgFormBean.getZddz() + "").trim();
//            String kssj = (zdjgFormBean.getKssj() + "").trim();
//            String jssj = (zdjgFormBean.getJssj() + "").trim();
////            Log.i("站点信息48================",zdjgFormBean.toString()+"");
//            int full_count48 = 0;
//            int full_count60 = 0;
//            if (Tools.isEmpeyNull(zdjgFormBean.getFull_count48())) {
//                full_count48 = Integer.parseInt(zdjgFormBean.getFull_count48());
//            }
//            if (Tools.isEmpeyNull(zdjgFormBean.getFull_count60())) {
//                full_count60 = Integer.parseInt(zdjgFormBean.getFull_count60());
//            }
//            String zddm = zdjgFormBean.getZddm();
//            int totalCount = full_count48 + full_count60;
//            Integer pointType = Integer.valueOf(zdjgFormBean.getZd_type());
//            if (pointType != null) {
//                if (pointType == 0) {
//                    //普通站
//                    ivBattery.setImageResource(R.mipmap.main_service_point2);
//                } else if (pointType == 1) {
//                    //服务站
//                    ivBattery.setImageResource(R.mipmap.main_service_point1);
//                }
//            }

//            tvBatteryNumber.setText(totalCount + "");
            BitmapDescriptor bitmap = BitmapDescriptorFactory.fromView(view_mark);
            // 构建MarkerOption，用于在地图上添加Marker
            option = new MarkerOptions().icon(bitmap).position(list_LatLng.get(i));
            // 设置marker里面的信息
            mMarkerA = (Marker) (mBaiduMap.addOverlay(option));
            markers.add(mMarkerA);
            mMarkerA.setPerspective(true);
            mMarkerA.setToTop();
            mMarkerA.setFlat(true);
            mMarkerA.setTitle(zdjgFormBean.getSiteNum());
            // 设置Marker覆盖物的ZIndex
            option.zIndex(999);
        }
    }


    // 开始地图相关动作
    private void startMapAction(boolean isNeedMove) {
        // 获取坐标点(模拟，实际为后台返回坐标，需异步加载)
        // getPoints();
        // 根据点绘制Marker

        showLineMarker();
        // 比较选出集合中最大经纬度
        getMax();
        // 计算两个Marker之间的距离
        calculateDistance();


    }

    /**
     * 计算两个Marker之间的距离
     */
    private void calculateDistance() {
        distance = GeoHasher.GetDistance(maxLatitude, maxLongitude,
                minLatitude, minLongitude);
    }

    private List<Double> latitudeList = new ArrayList<Double>();
    private List<Double> longitudeList = new ArrayList<Double>();
    private double maxLatitude;
    private double minLatitude;
    private double maxLongitude;
    private double minLongitude;

    /**
     * 比较选出集合中最大经纬度
     */
    private void getMax() {
        try {
            latitudeList.clear();
            longitudeList.clear();
            if (list_LatLng.size() > 0) {
                for (int i = 0; i < list_LatLng.size(); i++) {
                    double latitude = list_LatLng.get(i).latitude;
                    double longitude = list_LatLng.get(i).longitude;
                    latitudeList.add(latitude);
                    longitudeList.add(longitude);
                }
                maxLatitude = Collections.max(latitudeList);
                minLatitude = Collections.min(latitudeList);
                maxLongitude = Collections.max(longitudeList);
                minLongitude = Collections.min(longitudeList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private float level;

    private double distance;

    /**
     * 根据距离判断地图级别
     */
    private void getLevel() {
        int zoom[] = {10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 1000, 2000,
                25000, 50000, 100000, 200000, 500000, 1000000, 2000000};
        Log.i("info", "maxLatitude==" + maxLatitude + ";minLatitude=="
                + minLatitude + ";maxLongitude==" + maxLongitude
                + ";minLongitude==" + minLongitude);
        Log.i("info", "distance==" + distance);

        if (maxLatitude == minLatitude && maxLongitude == minLongitude) {
            mBaiduMap.setMapStatus(MapStatusUpdateFactory
                    .newMapStatus(new MapStatus.Builder().zoom(MAP_ZOOM_DEFAULT)
                            .build()));
            return;
        }
        for (int i = 0; i < zoom.length; i++) {
            int zoomNow = zoom[i];
            if (zoomNow - distance * 1000 > 0) {
                level = 18 - i + 6;
                if (level > 12) {
                    level = level - 1;
                }
                // 设置地图显示级别为计算所得level
                mBaiduMap.setMapStatus(MapStatusUpdateFactory
                        .newMapStatus(new MapStatus.Builder().zoom(level)
                                .build()));
                break;
            }
        }
    }

    private LatLng center;

    /**
     * 计算中心点经纬度，将其设为启动时地图中心
     */
    private void setCenter(boolean isNeedMove) {
        center = new LatLng((maxLatitude + minLatitude) / 2,
                (maxLongitude + minLongitude) / 2);
        Log.i("info", "center==" + center);
        MapStatusUpdate status1 = MapStatusUpdateFactory.newLatLng(center);

        if (isNeedMove) {
            mBaiduMap.animateMapStatus(status1, 500);
        }
    }

    /*
     * 查询客服电话
     * */
//    public void volleQuery_Kefu() {
//        final Gson mGson = new Gson();
//        String url = Constants.QUERY_KEFU;
//        StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
//
//            @Override
//            public void onResponse(String s) {
//                dismisProgressDialog();
//                Log.i("查询客服电话", s);
//                //s为请求返回的字符串数据
//                try {
//                    JSONObject json = new JSONObject(s);
//                    String code = json.getString("code");
//                    String msg = json.getString("message");
//                    if (code.equals("1")) {
//                        JSONObject data = json.getJSONObject("data");
//                        kefuPhone = data.getString("kfdh");
//                    } else {
//                        Tools.toast(msg);
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//        }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError volleyError) {
//            }
//        }) {
//            @Override
//            protected Map<String, String> getParams() throws AuthFailureError {//创建请求参数
//
//                HashMap<String, String> map = new HashMap<String, String>();
//                BljlFormBean mbljlFormBean = new BljlFormBean();
//                map.put("inputParameter", mGson.toJson(mbljlFormBean));
//                return map;
//            }
//        };
//        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
//    }



    /*
     * 查询电池电量
     * */
//    public void volleQuery_BatteryDian() {
//        String url = Constants.QUERY_BATTERY_DIAN;
//        StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
//
//            @Override
//            public void onResponse(String s) {
//                dismisProgressDialog();
//                Log.i("查询电池电量", s);
//                //s为请求返回的字符串数据
//                try {
//                    JSONObject json = new JSONObject(s);
//                    String code = json.getString("code");
//                    String msg = json.getString("message");
//                    if (code.equals("1")) {
//                        JSONObject data = json.getJSONObject("data");
//                        double dlsoc = Double.parseDouble(data.getString("soc"));
//                        String registStatus = data.getString("registStatus");
////              如果是空
//                        if (!Tools.isEmpeyNull(registStatus) || registStatus.equals("0")) {
//
//                            txtBatteryTitle.setVisibility(View.GONE);
//                            imgLixian.setVisibility(View.VISIBLE);
//                        } else {
//                            txtBatteryTitle.setVisibility(View.VISIBLE);
//                            imgLixian.setVisibility(View.GONE);
//                            if (dlsoc >= 0) {
//                                if (dlsoc > 80.00) {
//                                    txtBatteryTitle.setBackgroundResource(R.mipmap.main_battery_3);
//                                } else if (dlsoc > 50 && dlsoc <= 80.00) {
//                                    txtBatteryTitle.setBackgroundResource(R.mipmap.main_battery_2);
//                                } else if (dlsoc > 30 && dlsoc <= 50.00) {
//                                    txtBatteryTitle.setBackgroundResource(R.mipmap.main_battery_1);
//                                } else if (dlsoc <= 30) {
//                                    txtBatteryTitle.setBackgroundResource(R.mipmap.ima_dc_empty);
//                                    zhendong();
//                                    new CountDownTimer(2000, 1000) {
//                                        @Override
//                                        public void onTick(long millisUntilFinished) {
//                                        }
//
//                                        @Override
//                                        public void onFinish() {
//                                            Tools.showSound(R.raw.done, MainActivity.this);
//                                        }
//                                    }.start();
//
//
//                                }
//                                txtBatteryTitle.setText(dlsoc + "%");
//                            } else {
//                                txtBatteryTitle.setVisibility(View.GONE);
//                                imgLixian.setVisibility(View.VISIBLE);
//                            }
//                        }
////
//                    } else {
//                        Tools.toast(msg);
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//        }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError volleyError) {
//            }
//        }) {
//            @Override
//            protected Map<String, String> getParams() throws AuthFailureError {//创建请求参数
//                HashMap<String, String> map = new HashMap<String, String>();
//                map.put("inputParameter", Tools.getBatteryJson());
//                return map;
//            }
//        };
//        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
//    }


    //    没电震动
    private void zhendong() {
        Vibrator vibrator = (Vibrator) this.getSystemService(Service.VIBRATOR_SERVICE);
        long[] patter = {1000, 1000, 2000, 50};
        vibrator.vibrate(patter, -1);
    }

    private AlertDialog mDyDialog;
    private int selectDy = -1;

    private void shouDyDialog() {
        final String[] items = {"48V电池", "60V电池"};
        selectDy = -1;
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(MainActivity.this);
        alertBuilder.setTitle("请选择首放电池类型");
        alertBuilder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                //  Toast.makeText(Stu00.this, items[i], Toast.LENGTH_SHORT).show();
                selectDy = i;
            }
        });

        alertBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                if (selectDy < 0) {
                    return;
                }
                mDyDialog.dismiss();
                tzErweima();
            }
        });
        alertBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                mDyDialog.dismiss();
            }
        });
        alertBuilder.setCancelable(false);

        mDyDialog = alertBuilder.create();
        WindowManager.LayoutParams lp;
        lp = mDyDialog.getWindow().getAttributes();
        lp.gravity = Gravity.CENTER;
        mDyDialog.getWindow().setBackgroundDrawableResource(R.color.white);
        mDyDialog.getWindow().setAttributes(lp);
        selectDy = -1;
        mDyDialog.show();
    }


    /*
     * 邮政选择
     * */
    int yourChoice;

    private void showSingleChoiceDialog() {
        final String[] items = {"扫描电池码", "手动输入电池码"};
        yourChoice = 0;
        AlertDialog.Builder singleChoiceDialog =
                new AlertDialog.Builder(MainActivity.this);
        singleChoiceDialog.setTitle("请选择绑定电池方式");
        // 第二个参数是默认选项，此处设置为0
        singleChoiceDialog.setSingleChoiceItems(items, 0,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        yourChoice = which;
                    }
                });
        singleChoiceDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (yourChoice == 0) {

                            tzErweima();
                        } else {
//                            startAction(DC_edit_erweimaActivity.class);
                        }
                    }
                });
        singleChoiceDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                        dialog.dismiss();
                    }
                });
        singleChoiceDialog.show();
    }


    /*
     * 计时器工作
     * */
    private void timeOpen() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer.onFinish();
            countDownTimer = null;
        }
        countDownTimer = new CountDownTimer(1000 * 29, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                isDC = false;
                hcbj = 0;
//                toast("扫描电池超时，请扫柜子。。。");
            }
        }.start();
    }

    /*
     * 结束计时器
     * */
    private void closeTime() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer.onFinish();
            countDownTimer = null;
            isDC = false;
            hcbj = 0;
        }
    }


    private void getLocation() {
        // 获取位置管理服务
        LocationManager locationManager;
        String serviceName = Context.LOCATION_SERVICE;
        locationManager = (LocationManager) this.getSystemService(serviceName);
        // 查找到服务信息
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE); // 高精度
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        //设置是否要求速度
        criteria.setSpeedRequired(true);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW); // 低功耗
        String provider = locationManager.getBestProvider(criteria, true); // 获取GPS信息
        /**这段代码不需要深究，是locationManager.getLastKnownLocation(provider)自动生成的，不加会出错**/
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PERMISSION_GRANTED) {
            // TODO: Consider calling
            // ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            // public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //           int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location location = locationManager.getLastKnownLocation(provider); // 通过GPS获取位置
        updateLocation(location);

//        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 1, new LocationListener() {
//            @Override
//            public void onLocationChanged(Location location) {
//
//            }
//
//            @Override
//            public void onStatusChanged(String s, int i, Bundle bundle) {
//
//            }
//
//            @Override
//            public void onProviderEnabled(String s) {
//
//            }
//
//            @Override
//            public void onProviderDisabled(String s) {
//
//            }
//        });
    }

    private void updateLocation(Location location) {
        if (location != null) {
            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
//            Toast.makeText(this, "经度" + latitude + "纬度" + longitude, Toast.LENGTH_SHORT).show();
            LatLng pos = new LatLng(latitude, longitude);
            MapStatus.Builder builder = new MapStatus.Builder();
            builder.target(pos).zoom(MAP_ZOOM_DEFAULT);
            //镜头转至定位点
            MapStatusUpdate mapStatusUpdate =
                    MapStatusUpdateFactory.newMapStatus(builder.build());
            mBaiduMap.animateMapStatus(
                    mapStatusUpdate);

        } else {
//            Toast.makeText(this, "无法获取到位置信息", Toast.LENGTH_SHORT).show();
        }

    }


    /*
     * 查询城市
     * */
    public void volleQuery_City(String cityCode, String name) {
        String url = Constants.QUERY_CITY_CODE;
        StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {

            @Override
            public void onResponse(String s) {
                dismisProgressDialog();
                Log.i("查询城市", s);
                //s为请求返回的字符串数据
                try {
                    JSONObject json = new JSONObject(s);
                    String code = json.getString("code");
                    String msg = json.getString("message");
                    if (code.equals("1")) {
                        Constants.CITYID = cityCode;
                        JSONObject data = json.getJSONObject("data");
                        double cswd = data.getDouble("cswd");
                        double csjd = data.getDouble("csjd");
                        String scbj = data.getString("scbj");
                        if (scbj.equals("0")) {
                            // 地图移到选中城市
                            LatLng pos = new LatLng(cswd, csjd);
                            MapStatus.Builder builder = new MapStatus.Builder();
                            builder.target(pos).zoom(MAP_ZOOM_DEFAULT);
                            //镜头转至定位点
                            MapStatusUpdate mapStatusUpdate =
                                    MapStatusUpdateFactory.newMapStatus(builder.build());
                            mBaiduMap.animateMapStatus(
                                    mapStatusUpdate);
                            changeCity = true;
                            txtCity.setText(name);
                        } else {
                            toast("该城市尚未开通服务");
                        }

                    } else {
                        Tools.toast(msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {//创建请求参数

                HashMap<String, String> map = new HashMap<String, String>();
                String json = "{\"csdm\":\"" + cityCode + "\"}";
                map.put("inputParameter", json);
                return map;
            }
        };
        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 233 && resultCode == RESULT_OK) {
            if (data != null) {
                String city = data.getStringExtra(CityPickerActivity.KEY_PICKED_CITY);
                String name = data.getStringExtra(CityPickerActivity.KEY_PICKED_NAME);
                System.out.println("城市----" + city);
                volleQuery_City(city, name);
            }
        }
        // 扫描二维码/条码回传
        if (requestCode == Constants.ZXINGE_MAIN && resultCode == RESULT_OK) {
            if (data != null) {
                String content = data.getStringExtra(Constant.CODED_CONTENT);
                assert content != null;
                Log.i("扫描结果为", content);
                try {
                    JSONObject dataJson = new JSONObject(content);
                    String code = dataJson.getString("code");
                    Log.i("扫描结果为JSON", code);

//                    volleErweima(code);
                } catch (JSONException e) {
                    e.printStackTrace();
//                    volleErweima(content);
                }
            }
        }
    }


    /*
     * 跳转二维码界面
     * */
    private void tzErweima() {
        Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
        ZxingConfig config = new ZxingConfig();
        config.setShowAlbum(false);
        intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
        startActivityForResult(intent, Constants.ZXINGE_MAIN);
    }


    private String date2TimeStamp(String date, String format) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return String.valueOf(sdf.parse(date).getTime() / 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

}
